package com.siyoumi.app.modules.sh.task.jm;

import com.siyoumi.exception.EnumSys;
import com.siyoumi.util.XHttpClient;
import com.siyoumi.util.XLog;
import com.siyoumi.util.XReturn;
import com.siyoumi.util.XStr;

import java.util.HashMap;
import java.util.Map;

public abstract class TaskBase {
    abstract public void exec();

    abstract protected Map<String, String> getArrTask();

    abstract protected Map<String, String> getArrWxFrom();

    //通用任务处理
    protected String commonHandle(Map.Entry<String, String> task) {
        StringBuilder sendMsg = new StringBuilder();
        String taskName = task.getKey();
        sendMsg.append("**" + taskName + "** \n\n");

        Map<String, String> arrWxFrom = getArrWxFrom();
        String url = task.getValue();
        for (Map.Entry<String, String> entry : arrWxFrom.entrySet()) {
            String userName = entry.getKey();
            String apiUrl = url.replace("{wx_from}", entry.getValue());
            XReturn r = requestApi(apiUrl);

            sendMsg.append(XStr.concat(userName, ":", r.getErrMsg(), "\n\n"));
        }

        return sendMsg.toString();
    }

    /**
     * 获取wx_from
     *
     * @param s
     */
    public String getWxFrom(String s) {
        if (XStr.isNullOrEmpty(s)) {
            return null;
        }

        Map<String, String> mapWxFrom = new HashMap<>();

        String[] sArr = s.split("&");
        for (String f : sArr) {
            String[] fArr = f.split("=");
            mapWxFrom.put(fArr[0], fArr[1]);
        }

        return mapWxFrom.get("wx_from");
    }

    //请求
    public XReturn requestApi(String url) {
        //添加请求头
        Map<String, String> headers = new HashMap<>();
        headers.put("apixAuth", "1");

        XReturn r;
        try {
            XHttpClient client = XHttpClient.getInstance();
            String returnStr = client.get(url, headers);
            r = XReturn.parse(returnStr);

            XLog.debug(this.getClass(), url);
            XLog.debug(this.getClass(), returnStr);
        } catch (Exception ex) {
            ex.printStackTrace();
            XLog.error(this.getClass(), ex.getMessage());
            r = EnumSys.API_ERROR.getR(ex.getMessage());
        }

        if (r.ok() && XStr.isNullOrEmpty(r.getErrMsg())) {
            r.setErrMsg("成功");
        }

        return r;
    }
}
